#!/usr/bin/env python
# -*- coding: utf-8 -*-

from mm import *

class Mm_SQL(Mm):
	"""
	Rodic bjektu pro ziskani dat z SQL DB (MySQL, PostgreSQL, sqlite)
	"""
	def __init__(self, config):
		
		# rozparsuje retezec "config", ktery obsahuje dulezite 
		# informace ve tvaru "typ_databaze;uzivatel;heslo;databaze;tabulka"
		# jednitlive polozky jsou oddeleny strednikem
		config_items = self.parse(config)
		
		# provede se jen tehdy, je-li zadan spravny pocet parametru
		if len(config_items) == 6:
			it = iter(config_items)
			_type = it.next()
				
			#rozhozeni do pomocnych promennych, ciste pro prehlednost
			host = it.next()	
			user = it.next()
			password = it.next()
			database = it.next()
			table = it.next()
					
			self.set_status(_type, user, password, database, table)
			
		self.db_data = ()
		self.db_cursor = None
		self.db_query = None
		self.db_connection = None
		
		

	def get_status(self):
		return self.status
	
	def set_status(self, dbtype=None, user=None, password=None, database=None, table=None):
		if dbtype is not None:
			self.status['_type'] = dbtype
		
		if user is not None:
			self.status['user'] = user
		
		if password is not None:
			self.status['password'] = password
		
		if database is not None:
			self.status['database'] = database
		
		if table is not None:
			self.status['table'] = table
			
		return self.status

	def close(self):
		try:
			self.db_cursor.close()
			self.db_connection.close()
			print "The connection was succefully closed."
			return 1
		except:
			print "I can not close the connection."
			return None

	def try_connect(self, status):
		pass

	def connect(self):
		if self.db_connection:
			print "connect(): Connection already exist. OK"
		else:
			stat = self.get_status()
		
			db = self.try_connect(stat)
	
			if(db):
				self.db_cursor = db.cursor()
				self.db_connection = db
				return self.db_cursor
			else: 
				print "connect(): Database error. Sorry."
				return None

	def read(self, query = None):
		if not query:
			query = "SELECT * FROM " + self.status['table']
			
		return self.execute(query)
		

	def execute(self, _query):
		if not self.db_connection:
			try:
				self.connect()
			except:
				return None
		try:
			self.db_cursor.execute(_query)
			self.db_data = self.db_cursor.fetchall()
		except:
			print "execute(): Database error, sorry"

		# Prevedeni vysledku na seznam
		self.data = list(map(list, self.db_data))
		
		return self.data
		
	def get_items(self):
		"""Vrati seznam nazvu sloupcu v tabuce."""
		items = []
		if not self.db_connection:
			self.connect()
		
		for i in self.db_cursor.description:
			items.append(i[0])
		
		return items
		
		
class Mm_MySQL(Mm_SQL):
	"""
	"""
	
	def __init__(self, config):
		Mm_SQL.__init__(self, config)
		global MySQLdb
		MySQLdb = None
	
		try:
			import MySQLdb
		except:
			print "Module MySQLdb is not installed."
			return 
		
	def try_connect(self, stat):
		
		try:
			db = MySQLdb.connect(host='localhost', user=stat['user'], passwd=stat['password'], db=stat['database'])	
		except MySQLdb.OperationalError, e:
			print "try_connect(): Sorry, I can not connect to MySQL"
			return
		
		return db

class Mm_PgSQL(Mm_SQL):
	"""
	"""
	
	def __init__(self, config):
		Mm_SQL.__init__(self, config)
		global pyPgSQL
		pyPgSQL = None

		try:
			import pyPgSQL
		except:
			print "Module pyPgSQL is not installed."
			return
		
		def try_connect(self, stat):
			try:
				db = pyPgSQL.connect(host='localhost', user=stat['user'], passwd=stat['password'], db=stat['database'])
			except:
				print "try_connect(): Sorry, I can not connect to PostgreSQL"
				return
			
			return db

class Mm_sqlite(Mm_SQL):
	"""
	"""
	
	def __init__(self, config):
		Mm_SQL.__init__(self, config)
		global sqlite
		sqlite = None
		self.cursor = None
		
		try:
			from pysqlite2 import dbapi2 as sqlite
			#import sqlite
		except ImportError:
			#from pysqlite2 import dbapi2 as sqlite
			import sqlite
		except:
			print "Module (py)sqlite is not installed."
			return

	def try_connect(self, stat):
		try:
			db = sqlite.connect(stat['database'])
		except:
			print "try_connect(): Sorry, I can not connect to sqlite."
			return
			
		return db

if __name__=="__main__":
	s = Mm_sqlite("sqlite;;;;/home/bobin/data/ex1;t")
	print s.get_status()
	s.connect()
	print s.execute("SELECT jmeno FROM adresar")
	print s.read()
	#print s.read("SELECT jmeno from t")
	s.close()

	#import sqlite
	#from pysqlite2 import dbapi2 as sqlite
	#con = sqlite.connect("/home/bobin/data/ex1")
	#cur = con.cursor()
	#cur.execute("SELECT * FROM t")
	#print cur.fetchone()

#s.read()
#print s.get_data()
#s = Mm_MySQL("MySQL;localhost;root;;mysql;user")
#print s.get_status()
#s.connect()
#s.read()
#print s.get_data()
#print s.db_connection
#s.close()
#print s.get_items()
#s.set_status(table="db")
#s.read()
#print s.get_data()
#s.close()
# TESTY
#s = Mm_MySQL("MySQL;localhost;bobin;;mysql;bakalar")
#print s.get_status()
#s.connect()
#s.read()
#print s.get_data()
#print s.get_items()
#s.close()